package com.cxx.purchasecharge.component.controller;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.MemorialDayTypeBean;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.MemorialDayType;
import com.cxx.purchasecharge.dal.MemorialDayTypeDao;

@Controller
@RequestMapping ("/memorialDayType")
public class MemorialDayTypeManager
{
    private static final Logger logger = Logger.getLogger (MemorialDayTypeManager.class);

    @Autowired
    private MemorialDayTypeDao memorialDayTypeDao;

    @RequestMapping (value = "/")
    public String redirectToMemorialDayTypeManagement (ModelMap model)
    {
        return "memorialDayTypeManagement";
    }

    @RequestMapping (value = "/checkExist", method = RequestMethod.POST)
    public @ResponseBody
    String checkExist (@RequestParam String memorialDayTypeId, @RequestParam String name)
    {
        if (StringUtils.isBlank (memorialDayTypeId))
        {
            // new
            MemorialDayType obj = memorialDayTypeDao.findByName (name);
            if (null != obj)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long id = Long.parseLong (memorialDayTypeId);
            MemorialDayType memorialDayType = memorialDayTypeDao.findByName (name);
            if (null != memorialDayType && memorialDayType.getId () != id)
            {
                return "false";
            }
        }

        return "true";
    }

    @RequestMapping (value = "/getAllType", method = RequestMethod.POST)
    public @ResponseBody
    String getMemorialDayTypes (DataGridRequestForm dataGridRequestForm)
    {
        List <MemorialDayType> units = (List <MemorialDayType>) memorialDayTypeDao.findAll ();

        JSONArray jsonObject = JSONArray.fromObject (units);
        return jsonObject.toString ();
    }

    @RequestMapping (value = "/newMemorialDayType", method = RequestMethod.POST)
    public @ResponseBody
    String addMemorialDayType (MemorialDayTypeBean unitBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            MemorialDayType unit = new MemorialDayType (unitBean.getName ());
            String unitId = unitBean.getId ();
            if (null != unitId && !"".equals (unitId))
            {
                unit.setId (Long.parseLong (unitId));
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                memorialDayTypeDao.save (unit);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_MEMORIAL_DAY_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_MEMORIAL_DAY_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/updateMemorialDayType", method = RequestMethod.POST)
    public @ResponseBody
    String updateMemorialDayType (MemorialDayTypeBean unitBean, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors ())
        {
            logger.error (bindingResult.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            MemorialDayType unit = new MemorialDayType (unitBean.getName ());
            String unitId = unitBean.getId ();
            if (null != unitId && !"".equals (unitId))
            {
                unit.setId (Long.parseLong (unitId));
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                memorialDayTypeDao.save (unit);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_MEMORIAL_DAY_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_FAIL,
                                                                                       ComponentConstants.MSG_MEMORIAL_DAY_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @RequestMapping (value = "/delMemorialDayType", method = RequestMethod.POST)
    public @ResponseBody
    String deleteMemorialDayType (@RequestParam String ids)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            List <MemorialDayType> memorialDayTypes = new ArrayList <MemorialDayType> ();
            MemorialDayType memorialDayType;
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String typeId : idArr)
                {
                    memorialDayType = new MemorialDayType ();
                    memorialDayType.setId (Long.parseLong (typeId));
                    memorialDayTypes.add (memorialDayType);
                }
            }
            else
            {
                memorialDayType = new MemorialDayType ();
                memorialDayType.setId (Long.parseLong (ids));
                memorialDayTypes.add (memorialDayType);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                memorialDayTypeDao.delete (memorialDayTypes);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_MEMORIAL_DAY_TYPE))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_FAIL,
                                                                                       ComponentConstants.MSG_MEMORIAL_DAY_TYPE))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST);
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }
}
